<?php
/**
 * @name myMsSQL Project
 * @copyright GPL
 * @author Hakan DAMAR
 * @abstract Data Access Layer
 */
require_once 'inc/config.php';

class DB extends SystemConfig {
	private static $dbObject;
	private $server;
	private $ConnStr;
	private $query;
	public  $Conn;

	/**
	 * SQL Server Connection.
	 *
	 * @param string $server
	 * @param array $connectionString
	 * @return bool
	 */
	private function __construct(){
		
		$server = parent::_getServer();
		$this->server = $server;
		
		$connectionString = parent::_getConfig();
		$this->ConnStr = $connectionString;
		
		$connection =  sqlsrv_connect($this->server,$this->ConnStr);
		!$connection ? exit("SQL Server Not Connected!. <br>".print_r(sqlsrv_errors())) : $this->Conn = $connection;
		
		return true;
	}
	
	/**
	 * Singleton Pattern
	 * @return DB Object
	 */
	public static function _getDBObject(){
		if(!isset(self::$dbObject)){
			$class = __CLASS__;
			self::$dbObject = new $class;
		}
		return self::$dbObject;
	}
	
	/**
	 * Exec SQL Server Query
	 *
	 * @param string $query
	 */
	public function execQuery($query){
		$runQuery = sqlsrv_query($this->Conn,$query);
		!$runQuery ? exit("Error: ".print_r(sqlsrv_errors())) : $this->query = $runQuery;
		return $runQuery;
	}
	
	/**
	 * Free SQL Query Result..
	 * @return void
	 */
	public function freeResult(){
		if($this->query != null){
			sqlsrv_free_stmt($this->query);
		}else{
			throw new Exception("Exception: Query memory already free!");
			exit;
		}
		return true;
	}
		
	/**
	 * Close the sql connection.
	 *
	 */
	public function disconnect(){
		sqlsrv_close($this->Conn);
		return true;
	}
	
	/**
	 * Clone Protection
	 * @return void
	 */
	public function __clone(){
		trigger_error("ERROR: You Don't have a class clone access!",E_USER_NOTICE);
		exit;
	}
	
	/**
	 * WakeUp Controller
	 * @return void
	 */
    public function __wakeup(){
    	trigger_error('ERROR: Deserializing is not allowed.', E_USER_ERROR);
    	exit;
    }
	
	/**
	 * Undefined Function Calling
	 *
	 * @param string $name
	 * @param array $arr
	 */
	public function __call($name,$arr){
		print_r($arr);
		print("No {$name} method!");
	}
	
	/**
	 * Class Information
	 *
	 * @return string
	 */
	public function __toString(){
		return __CLASS__." Data Access Layer Object";
	}
	
	/**
	 * Other Controller
	 * @return void
	 */
	public function __destruct(){ 
		
	}
}	
?>